<template>
    <div class="wrap">
        <div class="form">
            <div class="left">
                <video src="../../assets/video/video.mp4" muted loop autoplay></video>
            </div>
            <h1 class="bt">CRM系统管理</h1>
            <div class="right">
                <i @click="isErweiLogin=!isErweiLogin" :class="['jiaobiao', 'iconfont',isErweiLogin?'icon-diannaojiaobiao':'icon-erweimajiaobiao' ]"></i>

               <el-form v-if="!isErweiLogin" :model="loginFrom" status-icon :rules="rules" ref="loginFrom" label-width="100px" class="login-ruleForm">
  
            <el-form-item  label="用户名" prop="username" class="name">
                <el-input type="text" id="text" v-model="loginFrom.username" auto-complete="off"></el-input>
            </el-form-item>

            <el-form-item  label="密码" prop="password" class="password">
                <el-input type="password" id="text" v-model="loginFrom.password" auto-complete="off"></el-input>
            </el-form-item>
            
            <el-form-item  label="验证码" prop="captcha">
                <el-input ref="captcha" @keydown.native.enter="submitForm('loginFrom')"  div-width="370px" class="text-yzm" v-model="loginFrom.captcha"></el-input>
                <p @click="updateCaptcha" class="captcha-svg" v-html="captchaSvg"></p>
            </el-form-item>
            

            <el-form-item  label-div="100%">
                <el-button type="primary" class="btn" @click="submitForm('loginFrom')">提交</el-button>
            </el-form-item>

            </el-form>
            <div v-else>
                <p class="ers">二维码登录</p>
                <img class="imgs" :src="qrDataUrl" alt="">
                <i class="mask" v-show="isScanCodeSue"><img src="../../assets/imges/扫码登录.gif" alt=""></i>
                <p class="frs">请使用微信扫一扫登录</p>
            </div>
            </div>
            
        </div>
    </div>
</template>
<script scoped>
        // 引入api中的方法
        import * as api from "../../api"
        import {mapMutations} from "vuex"
        // 引入socket.io
        // 引入生成二维码的插件qrcode
        import io from "socket.io-client"
        import qrcode from "qrcode"
       var validateCaptcha = (rule, value, callback) => {
         // callback 只要传参了，表示表单验证不通过，不传参表示表单验证通过
         // value就是在input中的输入值
         // rule是个对象，就是验证对象
         if(value.length!==5){
           callback("验证码长度错误")
         }else {
           callback()
         }
       };
       var validateUsername = (rule, value, callback) => {
         // callback 只要传参了，表示表单验证不通过，不传参表示表单验证通过
         // value就是在input中的输入值
         // rule是个对象，就是验证对象
         var reg = /^\w{3,12}$/
 
         if(reg.test(value)) {
             // 验证通过
             callback()
         }else{
           callback('用户名可以是字母数字下划线,3-12位')
         }
       };
       var validatePass = (rule, value, callback) => {
         var Pattern = /^\w{3,12}$/
        //  /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/
         if(Pattern.test(value)) {
           callback()
         } else {
           callback("密码最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符")
         }
       };
   export default {
       data() {
      return {
        isErweiLogin:false,//是否是二维码
        captchaSvg:"",//验证码svg
        loginFrom: {
          username: '',
          password: '',
          captcha: ''
        },
        rules: { //表单验证图片的规则
          username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          captcha: [
            { validator: validateCaptcha, trigger: 'blur' }
          ]
        },
        qrDataUrl:"",//二维码base64的图片地址
        isScanCodeSue:false,//是否扫码成功
      };
    },
    created() {
        // console.log(process.env.VUE_APP_BASE_URL);
        this.updateCaptcha()
    },
    methods:{
        ...mapMutations(['SET_USER_INFO']),
        // 封装一个方法，专门用于获取验证码
        updateCaptcha() {
            api.getCaptchaApi()
            .then(res=> {
                this.captchaSvg = res.data.img
            })
        },
        submitForm(formName) {
            // console.log(this.$refs[formName]);
        this.$refs[formName].validate((valid) => {
            // 所有的表单校验通过之后，那么valid的值是true
            // 要不然valid的布尔值是false

            // 1.先校验本地的表单是否通过
            // 2.效验验证码是否正确
            // 3.效验用户名密码是否正确

          if (valid) { //表单校验不通过
            // alert('submit!');
            const loading = this.$loading({
            lock: true,
            text: '正在登录',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
            });
            api.verifyCaptcha(this.loginFrom.captcha.toLowerCase())
            .then(res => {
                // console.log(res);
                if(res.data.state) {
                    // 验证码通过
                    // 继续效验用户名和用户密码
                    api.loginApi(this.loginFrom.username,this.loginFrom.password)
                    .then(res => {
                            // console.log(res.data);
                            if(res.data.state) {
                                loading.close()
                                this.$message({
                                message: '登录成功！',
                                type: 'success',
                                duration:1000
                                });
                                // 登录成功
                                // 1.将token储存到本地
                                localStorage.setItem("xdw-token",res.data.token)
                                // 2.将userInfo存到本地
                                localStorage.setItem("xdw-userInfo",JSON.stringify(res.data.userInfo))
                                // 信息添加到vuex
                                this.SET_USER_INFO(res.data.userInfo)
                                // 3.跳转到主页
                                this.$router.push("/")
                            }else
                            {
                                loading.close()
                                // 登录失败,用户名或者密码错误
                                this.$message.error('登录失败用户或者密码错误');
                            }
                        })
                }else {
                    // console.log('验证码错误');
                    // 验证码错误,刷新验证码
                    this.$alert('验证码错误！！', '验证码', {
                    confirmButtonText: '确定',
                    callback: () => {
                        loading.close()//关闭加载动画
                        this.$message.error('验证码错误！！');
                        this.loginFrom.captcha = ""//清空验证码内容
                        this.$refs.captcha.focus()
                        this.updateCaptcha() //验证码错误刷新
                    }
                    });
                }
            })
          } else {
            this.$message({
            message: '请将下面错误信息栏进行修改！！',
            type: 'warning'
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    },
    watch:{ //监听切换二维码登入的字段
        isErweiLogin(newVal,oldVal) {
            if(newVal) {
                // 已经切换成二维码登录
                // 1.通过socke.io和服务器建立链接tocket
                let socket = io("wss://chst.vip")
                // 2.监听socket链接成功事件，发送请求，获取"/user/getScanCode"获取二维码地址
                socket.on("connectSuccess",(data)=> {
                    // let { sid } = data
                    // localStorage.setItem("qf-sid",sid)
                    // this.getQrcodeUrlApi()
                    // this.getQrcodeUrlApi()
                     api.getQrcodeUrlApi(data.sid)
                        .then((res) => {
                        // console.log(res);
                        let qrUrl = res.data.scanCodeUrl;
                        // 3.通过qrcode将二维码地址生成二维码
                        qrcode.toDataURL(qrUrl,(err,dataUrl) => {
                            // console.log(dataUrl);
                            this.qrDataUrl = dataUrl
                        })
                    })
                    // 4.用户扫描二维码
                    // 5.监听socket事件 scancodeSuccess(这个事件不是socket.io定义的,前后端约定的)
                    socket.on("scancodeSuccess",(data)=> {
                        // console.log("扫码成功");
                        // console.log(data);
                        // 6.请求users/wechatLogin，传递wechatCode
                        if(data.state) { //扫码成功
                            // 显示遮罩
                            this.isScanCodeSue = true
                             api.wechatLoginApi(data.wechatCode)
                             .then(res => {
                                //  将用户信息存起
                                if(res.data.state) {
                                    // 登录成功
                                    // 1.将token储存到本地
                                    localStorage.setItem("xdw-token",res.data.token)
                                    // 2.将userInfo存到本地
                                    localStorage.setItem("xdw-userInfo",JSON.stringify(res.data.userInfo))
                                    // 3.信息添加到vuex
                                    this.SET_USER_INFO(res.data.userInfo)
                                    // 跳转到首页
                                    this.$router.push("/")
                                }else {
                                    this.$message.error("微信登录失败")
                                }
                             })
                        }else 
                        {
                            // 提示扫码失败
                            this.$message.error("扫码失败")
                        }
                    // 判断成功和失败
                    })
                })
              
                
            }else {
                // 切换到普通登录
                // 关闭遮罩层
                this.isScanCodeSue = false
            }
            
        }
    }
   }
</script>

<style scoped>
    * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.mask {
    overflow: hidden;
    width: 300px;
    height: 300px;
    top: 128px;
    left: 50px;
    position: absolute;
    opacity: 0.9;
}

.mask img {
    position: absolute;
    left: -165px;
    height: 300px;
}

.frs {
    position: absolute;
    bottom: 50px;
    left: 110px;
    color: #00a1d6;
}

.imgs {
    margin: 0 16%;
    width: 300px;
    height: 300px;
}
.ers {
    position: absolute;
    top: 70px;
    left: 150px;
    color: #00a1d6;
}

body {
    margin: 0;
}

.captcha-svg {
    cursor: pointer;
    position: absolute;
    right: 0;
}

body {
    overflow: hidden;
}

.wrap {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: linear-gradient(to left top, #d16ba5, #c777b9, #ba83ca, #aa8fd8, #9a9ae1, #8aa7ec, #79b3f4, #69bff8, #52cffe, #41dfff, #46eefa, #5ffbf1);
}

.form {
    width: 900px;
    height: 560px;
    display: flex;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 25px 45px rgba(0, 0, 0, 0.1);
}

.left {
    width: 500px;
    height: 560px;
}
.bt {
    color: #366ae6;
    position: absolute;
}

.jiaobiao {
    color: #41dfff;
    font-size: 60px;
    position: absolute;
    right: -1px;
    top: -1px;
    cursor: pointer;
}

.left video {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.right {
    position: relative;
    width: 400px;
    height: 560px;
    background: rgba(255,255,255,0.9);
    display: flex;
    align-items: center;
}

.right-con {
    width: 70%;
    display: flex;
    flex-direction: column;
    text-align: center;
}

.el-form {
    margin: 0 10px;
}

h1 {
    font-size: 26px;
    color: #70b4e3;
    font-weight: 400;
    padding-bottom: 10px;
}

h3 {
    font-size: 12px;
    font-weight: 400;
    color: #70b4e3;
    padding: 20px 0;
}



 .el-input /deep/ .el-input__inner{
    outline: none;
    border: none;
    border-bottom: 1px solid #70b4e3;
    color: #366ae6;
    background-color: rgba(0, 0, 0, 0);
}

.el-form-item {
    margin-bottom: 35px;
}
.el-input /deep/ .el-input__inner {
    /* padding: 0 100px; */
    width: 370px;
}
.el-form-item /deep/ .el-form-item__error {
    line-height: 15px;
}

.el-form-item>>>.el-form-item__content {
    width: 100%;
    margin: 0 !important;
}

.el-form-item__label {
    width: auto !important;
}

.btn {
    width: 100%;
    height: 40px;
    border-radius: 20px;
    border: none;
    color: #fff;
    font-size: 16px;
    cursor: pointer;
    margin-top: 50px;
    background-image: linear-gradient(120deg, #76daec 0%, #c5a8de 100%);
}

.btn:hover {
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
</style>
